package cn.hqc.user.controller;


import cn.hqc.basic.utils.AjaxResult;
import cn.hqc.basic.utils.PageList;
import cn.hqc.user.domain.User;
import cn.hqc.user.dto.AccountLoginDto;
import cn.hqc.user.dto.BinderDto;
import cn.hqc.user.dto.PhoneRegisterDto;
import cn.hqc.user.dto.WechatDto;
import cn.hqc.user.query.UserQuery;
import cn.hqc.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    public IUserService userService;


    /**
     * 保存和修改公用的
     *
     * @param user 传递的实体
     * @return AjaxResult转换结果
     */
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody User user) {
        try {
            if (user.getId() != null)
                userService.update(user);
            else
                userService.add(user);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    /**
     * 删除对象信息
     *
     * @param id
     * @return
     */
    @DeleteMapping(value = "/{id}")
    public AjaxResult delete(@PathVariable("id") Long id) {
        try {
            userService.delete(id);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.fail();
        }
    }

    //获取用户
    @GetMapping("/{id}")
    public User get(@PathVariable("id") Long id) {
        return userService.findById(id);
    }


    /**
     * 查看所有的员工信息
     *
     * @return
     */
    @GetMapping()
    public List<User> list() {

        return userService.findAll();
    }


    /**
     * 分页查询数据
     *
     * @param query 查询对象
     * @return PageList 分页对象
     */
    @PostMapping("/list")
    public PageList<User> json(@RequestBody UserQuery query) {
        return userService.queryByPage(query);
    }


    /**
     * 手机号注册
     */
    @PostMapping("/phoneRegist")
    public AjaxResult phoneRegist(@RequestBody @Valid PhoneRegisterDto dto) {
        userService.phoneRegist(dto);
        return AjaxResult.success();
    }


    /**
     * 账号密码登录
     */
    @PostMapping("/account")
    public AjaxResult account(@RequestBody @Valid AccountLoginDto dto) {
        Map<String, Object> result = userService.accountLogin(dto);
        return AjaxResult.success(result);
    }

    /**
     * 微信扫码登录
     */
    @PostMapping("/account/wechat")
    public AjaxResult accountWechat(@RequestBody @Valid WechatDto dto) {

        return userService.accountWechat(dto);
    }

    /**
     * 微信扫码登录
     */
    @PostMapping("/account/binder")
    public AjaxResult accountBinder(@RequestBody @Valid BinderDto dto) {
        Map<String, Object> map = userService.accountBinder(dto);
        return AjaxResult.success(map);
    }
}
